/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: AliceMana
 * Date: 2023-01-08
 * Time: 16:29
 */

public class Solution {
    // https://leetcode.cn/problems/linked-list-cycle-ii/
    public static ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }

        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (fast == slow) {
                break;
            }
        }
        if (fast == null || fast.next == null) {
            return null;
        }
        slow = head;
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }


    // https://leetcode.cn/problems/reverse-linked-list/submissions/
    public static ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode cur = head;

        ListNode newNode = null;
        while (cur != null) {
            ListNode curNext = cur.next;
            cur.next = newNode;
            newNode = cur;
            cur = curNext;
        }
        return newNode;
    }

    public static void main(String[] args) {
        MySingleList list = new MySingleList();
        list.addLast(3);
        list.addLast(2);
        list.addLast(0);
        list.addLast(-4);
        list.createLoop();
        ListNode node = detectCycle(list.head);
        System.out.println();
    }
}
